import { VueTemplateCompiler } from "@vue/component-compiler-utils/lib/types";
import { UserConfig } from "../config";
import path from "path";
import fs from "fs";

const fsPromises = fs.promises;

export function isDir(str: string) {
  // TODO: 检测str 是否是路径
  return str[str.length - 1] === "/";
}

export function resolveCompiler(root: string): VueTemplateCompiler {
  // TODO: if user install some vue compiler, use user's first
  if (root) {
    return require("vue-template-compiler");
  }
  return require("vue-template-compiler");
}

export const isCss = /\.(css|less|sass|scss)$/;

// to resolve path for some import module.
// such as @/utils/index.js
export async function resolvePath(
  importPath: string,
  { alias = {}, extensions = [".js"] }: UserConfig,
  // the path which contan this importPath.
  filePath = ""
) {
  let s = importPath.slice();
  for (const key in alias) {
    if (s.startsWith(key)) {
      s = s.replace(key, alias[key]);
    }
  }
  if (path.extname(s.split("?")[0])) {
    return s;
  }
  // if no file,
  // transfer it to index.(js|vue) ..etc.
  try {
    await Promise.all(
      extensions.map(async (ext) => {
        return Promise.all([
          fsPromises
            .access(
              path.join(
                process.cwd(),
                path.dirname(filePath),
                `${importPath}.${ext}`
              ),
              fs.constants.R_OK
            )
            .then(() => (s = `${importPath}.${ext}`))
            .catch((e) => console.error(e)),
          fsPromises
            .access(
              path.join(
                process.cwd(),
                path.dirname(filePath),
                `${importPath}/index.${ext}`
              ),
              fs.constants.R_OK
            )
            .then(() => (s = `${importPath}/index.${ext}`))
            .catch((e) => console.error(e)),
        ]);
      })
    );
  } catch (e) {
    // TODO: delete on production mode
    console.error(e);
    return s;
  }
  return s;
}
